package cn.kooki.app.duobao.ui.Activity.User;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.socks.library.KLog;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.kooki.app.duobao.R;
import cn.kooki.app.duobao.base.BaseNavActivity;
import cn.kooki.app.duobao.base.BaseRecyclerAdapter;
import cn.kooki.app.duobao.core.APIService;
import cn.kooki.app.duobao.core.MainFactory;
import cn.kooki.app.duobao.data.Bean.Index.GoodsItem;
import cn.kooki.app.duobao.data.Bean.Index.IndexGoodResponse;
import cn.kooki.app.duobao.data.Bean.User.UserInfo;
import cn.kooki.app.duobao.data.Bean.User.win.WinItemInfo;
import cn.kooki.app.duobao.data.Bean.User.win.WinRecordResponse;
import cn.kooki.app.duobao.data.Bean.base.BaseResponse;
import cn.kooki.app.duobao.data.bus.ChangePageEvent;
import cn.kooki.app.duobao.data.constant.Constants;
import cn.kooki.app.duobao.ui.Activity.Goods.GoodsDetailAcitvity;
import cn.kooki.app.duobao.ui.Adapter.ListRecommAdapter;
import cn.kooki.app.duobao.ui.Adapter.RecordAdapter;
import cn.kooki.app.duobao.ui.view.CustomRefreshHeader;
import cn.kooki.app.duobao.ui.view.LoadMoreContainer;
import cn.kooki.app.duobao.ui.view.LoadMoreHandler;
import cn.kooki.app.duobao.ui.view.LoadMoreListViewContainer;
import cn.kooki.app.duobao.ui.widget.CustomRelativeLayout;
import cn.kooki.app.duobao.util.SharePreferencesUtils;
import cn.kooki.app.duobao.util.ShareUtils;
import de.greenrobot.event.EventBus;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * Created by xiong on 2015/12/18.
 */
public class WinRecordActivity extends BaseNavActivity implements View.OnClickListener, RecordAdapter.WinShareClickListener {
    @Bind(R.id.lv_winrecord)
    ListView lvWinrecord;
    @Bind(R.id.txt_empty_title)
    TextView txtEmptyTitle;
    @Bind(R.id.blank_go_duobao)
    Button blankGoDuobao;
    @Bind(R.id.layout_empty)
    LinearLayout layoutEmpty;
    @Bind(R.id.list_recommend)
    RecyclerView listRecommend;
    @Bind(R.id.emptyWrapper)
    ScrollView emptyWrapper;
    @Bind(R.id.loadingWrapper)
    CustomRelativeLayout loadingWrapper;
    @Bind(R.id.load_more_content_container)
    LoadMoreListViewContainer loadMoreContentContainer;
    @Bind(R.id.swipe_refresh_layout)
    PtrFrameLayout swipeRefreshLayout;
    private ListRecommAdapter listRecommAdapter;
    private RecordAdapter adapter;
    private UserInfo userinfo;
    private int page = 1;

    private ArrayList<WinItemInfo> datas = new ArrayList<>();
    private String content;
    private String url;
    private UMImage image;
    private String title;

    @Override
    public void setLayoutContainerView() {
        setContainerView(R.layout.activity_winrecord);
        ButterKnife.bind(this);

    }


    @Override
    protected void afterView() {
        setTitle(R.string.title_activity_mywinrecord);
        blankGoDuobao.setOnClickListener(this);
        userinfo = SharePreferencesUtils.getUserinfo(this);
        listRecommend.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        listRecommAdapter = new ListRecommAdapter(this);
        listRecommend.setAdapter(listRecommAdapter);
        listRecommAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, Object data) {
                GoodsItem item = (GoodsItem) data;
                Intent intent = new Intent(WinRecordActivity.this, GoodsDetailAcitvity.class);
                intent.putExtra("id", item.getId());
                intent.putExtra("qishu", item.getQishu());
                startActivity(intent);
            }
        });
        gettuijian();
        loadingWrapper.showloading();
        emptyWrapper.setVisibility(View.GONE);
        adapter = new RecordAdapter(this, datas);
        adapter.setWinShareClickListener(this);
        lvWinrecord.setAdapter(adapter);
        loadingWrapper.setRetryClickListener(new CustomRelativeLayout.onRetryClickListener() {
            @Override
            public void onRetry() {
                loadingWrapper.hideNetError();
                swipeRefreshLayout.autoRefresh(false);
            }
        });
        CustomRefreshHeader refreshHeader = new CustomRefreshHeader(this);
        swipeRefreshLayout.setHeaderView(refreshHeader);
        swipeRefreshLayout.addPtrUIHandler(refreshHeader);
        swipeRefreshLayout.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, lvWinrecord, header);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                getdata(false);
            }
        });
        loadMoreContentContainer.useDefaultFooter();
        loadMoreContentContainer.setShowLoadingForFirstPage(true);
        loadMoreContentContainer.setAutoLoadMore(true);
        loadMoreContentContainer.setLoadMoreHandler(new LoadMoreHandler() {
            @Override
            public void onLoadMore(LoadMoreContainer loadMoreContainer) {
                getdata(true);
            }
        });
        getdata(false);

    }

    private void getdata(final boolean b) {
        if (b) {
            page++;
        } else {
            page = 1;
        }
        MainFactory.getApiInstance().winlist(userinfo.getUid(), page, new Callback<WinRecordResponse>() {
            @Override
            public void success(WinRecordResponse baseResponse, Response response) {
                loadingWrapper.hideloading();
                if (baseResponse.data != null) {
                    if (!b) {
                        datas.clear();
                        if (baseResponse.data.size() == 0) {
                            emptyWrapper.setVisibility(View.VISIBLE);
                            swipeRefreshLayout.setVisibility(View.GONE);
                        } else {
                            swipeRefreshLayout.setVisibility(View.VISIBLE);
                            emptyWrapper.setVisibility(View.GONE);
                        }
                    }
                    datas.addAll(baseResponse.data);
                    adapter.notifyDataSetChanged();
                    if (!b) {
                        swipeRefreshLayout.refreshComplete();
                    }
                    loadMoreContentContainer.loadMoreFinish(datas.size() == 0, baseResponse.data.size() == Constants.DEFAULT_COUNT);
                } else {
                    emptyWrapper.setVisibility(View.VISIBLE);
                    swipeRefreshLayout.setVisibility(View.GONE);
                }
            }

            @Override
            public void failure(RetrofitError error) {
                if (error.getKind() == RetrofitError.Kind.NETWORK) {
                    loadingWrapper.showNetError();
                }
                if (!b) {
                    swipeRefreshLayout.refreshComplete();
                }
                loadMoreContentContainer.loadMoreError(200, "网络错误，请重试");
            }
        });
    }


    /**
     * 获取推荐商品
     */
    private void gettuijian() {
        MainFactory.getApiInstance().tuijianlist(new Callback<IndexGoodResponse>() {
            @Override
            public void success(IndexGoodResponse indexGoodResponse, Response response) {
                if (indexGoodResponse.getData() != null) {
                    listRecommAdapter.mDatas.clear();
                    listRecommAdapter.addDatas(indexGoodResponse.getData());
                }
            }

            @Override
            public void failure(RetrofitError error) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v == blankGoDuobao) {
            ChangePageEvent changePageEvent = new ChangePageEvent();
            changePageEvent.item = 0;
            EventBus.getDefault().post(changePageEvent);
            finish();
        }
    }

    @Override
    public void onShareClick(int position) {

        image = new UMImage(this, R.drawable.takeout_ic_coupon_wm);
        title = "朋友夺到宝，分给你了！";
        content = "一元收获惊喜，亲测有效！现在我把好运气人品都传给你，快来领取吧！";
        url = Constants.APP_SHARE_URL + userinfo.getUid();
        ShareUtils shareUtils = new ShareUtils();
        shareUtils.showShareDialog(this, new ShareUtils.shareItemClickLister() {
            @Override
            public void onClick(SHARE_MEDIA media) {
                if (media == SHARE_MEDIA.SINA) {
                    content = content + url;
                }
                new ShareAction(WinRecordActivity.this)
                        .setPlatform(media)
                        .setCallback(winsharelistener).withTitle(title).withMedia(image)
                        .withText(content).withTargetUrl(url)
                        .share();
            }
        });
    }


    private UMShareListener winsharelistener = new UMShareListener() {
        @Override
        public void onResult(SHARE_MEDIA share_media) {
            KLog.e("成功");
            MainFactory.getApiInstance().postBonus(userinfo.getUid(), 8, new Callback<BaseResponse>() {
                @Override
                public void success(BaseResponse baseResponse, Response response) {

                }

                @Override
                public void failure(RetrofitError error) {

                }
            });
        }

        @Override
        public void onError(SHARE_MEDIA share_media, Throwable throwable) {

        }

        @Override
        public void onCancel(SHARE_MEDIA share_media) {

        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }
}
